package com.mao.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mao.dao.LinuxDao;
import com.mao.pojo.LinuxPack;
import com.mao.pojo.User;

import org.apache.commons.io.FileUtils;
import org.springframework.util.ResourceUtils;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
  @Description: 
  @Param: 
  @Thought: 
  @Author: Wenjie Mao
  @create： 2022-11-21 18:08
*/
/*
 waiting to be edited
 */
public class JsonUtils {

    public void writeBeanToJson(Object o, String jsonURL){
        boolean result = false;
        BufferedWriter bufferedWriter = null;
        ObjectMapper mapper = new ObjectMapper();


        try {
            String jsonString = mapper.writeValueAsString(o);

            System.out.println(jsonString);

            File file = new File(jsonURL);

            bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));



            bufferedWriter.write(jsonString);


        } catch (IOException e) {
            System.out.println("保存数据到json文件异常！" + e);
        } finally {
            if (null != bufferedWriter) {
                try {
                    bufferedWriter.close();
                } catch (IOException exception) {
                    System.out.println("保存数据到json文件后，关闭流异常" + exception);
                }
            }
        }
    }

    public static void jsonToMysql(LinuxDao linuxDao, String jsonURL){
        try {
            File file = ResourceUtils.getFile(jsonURL);
            String jsonString = FileUtils.readFileToString(file);
            JSONArray jsonList = JSONObject.parseArray(jsonString);


            for (int i = 0; i < jsonList.size(); i++) {
                JSONObject jsonObject = jsonList.getJSONObject(i);
                LinuxPack linuxPack = jsonObject.toJavaObject(LinuxPack.class);
                System.out.println("inserting/t" + linuxPack.getName());
                linuxDao.insert(linuxPack);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
